package com.me.study.ui.activity

import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SizeUtils
import com.blankj.utilcode.util.ToastUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemChildClickListener
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.me.study.R
import com.me.study.app.base.BaseActivity
import com.me.study.app.data.NotifyType
import com.me.study.app.data.RichEditorType
import com.me.study.app.general.PictureUtil
import com.me.study.app.rvRichEditor.RichEditorAdapter
import com.me.study.app.rvRichEditor.RichEditorData
import com.me.study.app.rvRichEditor.listener.EditorCursorListener
import com.me.study.app.rvRichEditor.listener.EditorTouchListener
import com.me.study.databinding.ActivityRvRichEditorBinding
import com.yanzhenjie.recyclerview.widget.DefaultItemDecoration
import me.hgj.jetpackmvvm.base.viewmodel.BaseViewModel
import java.util.*

class RvRichEditorActivity : BaseActivity<BaseViewModel, ActivityRvRichEditorBinding>(),
    View.OnClickListener, OnItemChildClickListener, EditorTouchListener, EditorCursorListener {

    private val richEditorAdapter by lazy {
        RichEditorAdapter(this, this)
    }

    private var mPosition: Int = 0
    private var isAction: Boolean = false

    private var itemTouchHelper: ItemTouchHelper? = null

    override fun layoutId(): Int {
        return R.layout.activity_rv_rich_editor
    }

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.openImage.setOnClickListener(this)
        mDatabind.openVideo.setOnClickListener(this)
        mDatabind.ivData.setOnClickListener(this)
        mDatabind.rvRichEditor.layoutManager = LinearLayoutManager(this)
        mDatabind.rvRichEditor.adapter = richEditorAdapter
        mDatabind.rvRichEditor.addItemDecoration(
            DefaultItemDecoration(
                Color.TRANSPARENT,
                SizeUtils.dp2px(4f),
                SizeUtils.dp2px(4f)
            )
        )
        mDatabind.rvRichEditor.setItemViewCacheSize(0)
        richEditorAdapter.addChildClickViewIds(R.id.iv_close)
        richEditorAdapter.setOnItemChildClickListener(this)
        richEditorAdapter.addData(RichEditorData.getDefaultText())
        val callBack = ItemTouchHelperCallBack()
        itemTouchHelper = ItemTouchHelper(callBack)
        itemTouchHelper?.attachToRecyclerView(mDatabind.rvRichEditor)

    }

    inner class ItemTouchHelperCallBack : ItemTouchHelper.Callback() {

        override fun getMovementFlags(
            recyclerView: RecyclerView,
            viewHolder: RecyclerView.ViewHolder
        ): Int {
            val position = viewHolder.layoutPosition
            val adapter = recyclerView.adapter
            adapter?.let {
                if (adapter is RichEditorAdapter) {
                    val data = richEditorAdapter.data[position]
                    if (data.type == RichEditorType.TEXT.VALUE || data.type == RichEditorType.VIDEO.VALUE) {
                        return makeMovementFlags(0, 0)
                    }
                    val dragFlags = (ItemTouchHelper.UP or ItemTouchHelper.DOWN)
                    return makeMovementFlags(dragFlags, 0)
                }
            }
            return makeMovementFlags(0, 0)
        }

        override fun onMove(
            recyclerView: RecyclerView,
            viewHolder: RecyclerView.ViewHolder,
            target: RecyclerView.ViewHolder
        ): Boolean {
            val adapter = recyclerView.adapter
            adapter?.let { a ->
                if (a is RichEditorAdapter) {
                    a.onMove(
                        viewHolder.absoluteAdapterPosition,
                        target.absoluteAdapterPosition
                    )
                }
            }
            return true
        }

        override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {}

        override fun clearView(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) {
            viewHolder.let {
                val position = it.absoluteAdapterPosition
                val adapter = recyclerView.adapter
                adapter?.let { a ->
                    if (a is RichEditorAdapter) {
                        a.notifyItemChanged(position, NotifyType.END_MOVE.VALUE)
                        a.endMoveText()
                        if (position == 0) {
                            if (a.data[position].type == 1) {
                                richEditorAdapter.addData(0, RichEditorData.getDefaultText())
                                mDatabind.rvRichEditor.scrollToPosition(0)
                            }
                        }
                        if (a.data.size == position) {
                            mDatabind.rvRichEditor.scrollToPosition(a.data.size)
                        }
                    }
                }
            }
        }

        override fun onSelectedChanged(viewHolder: RecyclerView.ViewHolder?, actionState: Int) {
            viewHolder?.let {
                val position = it.absoluteAdapterPosition
                it.bindingAdapter?.let { a ->
                    if (a is RichEditorAdapter) {
                        a.notifyItemChanged(position, NotifyType.START_MOVE.VALUE)
                        a.startMoveText()
                        KeyboardUtils.hideSoftInput(this@RvRichEditorActivity)
                        mDatabind.rvRichEditor.clearFocus()
                    }
                }
            }
        }

        override fun isLongPressDragEnabled(): Boolean {
            return false
        }
    }

    override fun onClick(p0: View) {
        when (p0.id) {
            R.id.open_image -> {
                PictureUtil.openPhoto(this, object : OnResultCallbackListener<LocalMedia> {
                    override fun onResult(result: ArrayList<LocalMedia>?) {
                        result?.let {
                            when (richEditorAdapter.actionAddImage(mPosition - 1) && isAction) {
                                true -> {
                                    ToastUtils.showLong("true")
                                    for (item in it) {
                                        val path = item.realPath
                                        richEditorAdapter.addData(
                                            mPosition,
                                            RichEditorData(
                                                RichEditorType.IMAGE.VALUE,
                                                path,
                                                "", false, isFocusable = false
                                            )
                                        )
                                        richEditorAdapter.addData(RichEditorData.getDefaultText())
                                    }
                                    isAction = false
                                }
                                false -> {
                                    ToastUtils.showLong("false")
                                    for (item in it) {
                                        val path = item.realPath
                                        richEditorAdapter.addData(
                                            RichEditorData(
                                                RichEditorType.IMAGE.VALUE,
                                                path,
                                                "", false, isFocusable = false
                                            )
                                        )
                                        richEditorAdapter.addData(RichEditorData.getDefaultText())
                                    }
                                }
                            }
                            mDatabind.rvRichEditor.scrollToPosition(richEditorAdapter.data.size)
                        }
                    }

                    override fun onCancel() {}

                }, openGallery = SelectMimeType.ofImage())
            }
            R.id.open_video -> {
                PictureUtil.openPhoto(this, object : OnResultCallbackListener<LocalMedia> {
                    override fun onResult(result: ArrayList<LocalMedia>?) {
                        result?.let {
                            for (item in it) {
                                val path = item.realPath
                                richEditorAdapter.addData(
                                    mPosition,
                                    RichEditorData(
                                        RichEditorType.VIDEO.VALUE,
                                        path,
                                        "", isMove = false, isFocusable = false
                                    )
                                )
                                richEditorAdapter.addData(
                                    mPosition + 1,
                                    RichEditorData.getDefaultText()
                                )
                            }
                            mDatabind.rvRichEditor.scrollToPosition(richEditorAdapter.data.size)
                        }
                    }

                    override fun onCancel() {}

                }, openGallery = SelectMimeType.ofVideo())
            }
            R.id.iv_data -> {
                val data = richEditorAdapter.data
                LogUtils.d("data_data$data")
            }
        }
    }


    override fun onItemChildClick(p0: BaseQuickAdapter<*, *>, p1: View, p2: Int) {
        when (p1.id) {
            R.id.iv_close -> {
                richEditorAdapter.remove(p2)
                richEditorAdapter.notifyDataSetChanged()
            }
        }
    }

    override fun onItemDown(holder: RecyclerView.ViewHolder) {
        itemTouchHelper?.startDrag(holder)
    }

    override fun onItemPosition(actionId: Int, position: Int, isAdd: Boolean, isDelete: Boolean) {
        LogUtils.d("mPosition$position")
        mPosition = position + 1
        LogUtils.d("mPosition$mPosition")
        when (actionId) {
            EditorInfo.IME_ACTION_UNSPECIFIED -> {
                if (isAdd) {
                    isAction = true
                    richEditorAdapter.addData(mPosition, RichEditorData.getDefaultTextFocusable())
                }
            }
            -1 -> {
                if (isDelete) {
                    if (position != 0) {
                        richEditorAdapter.removeAt(position)
                        richEditorAdapter.notifyDataSetChanged()
                        if (position > 0) {
                            val upPosition = position - 1
                            val upData = richEditorAdapter.data[upPosition]
                            if (upData.type == RichEditorType.TEXT.VALUE) {
                                upData.isFocusable = true
                                richEditorAdapter.notifyItemChanged(upPosition)
                            } else {
                                KeyboardUtils.hideSoftInput(this)
                            }
                        }
                    }
                }
            }
        }
    }

}